// const express = require('express');
// const app = express();

//集成socket.io
const express = require("express");
const path = require("path");
const app = express();



const http = require("http");
const server = http.createServer(app);
app.use(express.static(__dirname + "/public")); //设置静态文件目录
const config = require("./config.default"); //保存全局变量
var moment = require("moment");
const Excel = require("exceljs");
// multer使用
//1需安装npm i multer
const multer = require("multer");
const mkdirp = require("mkdirp");
//2初始化中间件并设置上传目录
// const upload = multer({ dest: 'uploads/' })
const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    //自定义动态存储目录：譬如按日期
    //每天一个目录保存上传文件
    const day = moment().format("YYYYMMDD"); //使用moment需要npm i moment
    //组装路径uploads\20210109
    const dir = path.join("uploads", day);
    //异步创建多级目录
    await mkdirp(dir); //使用mkdirp（创建多级目录）需要npm i mkdirp
    cb(null, dir);
  },
  filename: (req, file, cb) => {
    //获取文件后缀
    const extname = path.extname(file.originalname);
    const uniqueSuffix =
      Date.now() + "-" + Math.round(Math.random() * 1e9) + extname;
    cb(null, file.fieldname + "-" + uniqueSuffix);
  },
});
const upload = multer({ storage: storage });

// const {
//   find,
//   insertOne,
//   update,
//   updateMany,
//   distinct,
//   deleteMany,
//   extendFunc,
// } = require("./mongo");

app.all("*",function(req,res,next){
  // 设置允许跨域的域名,*代表允许任意域名跨域
  res.header('Access-Control-Allow-Origin','*');
  // 允许的header类型
  res.header('Access-Control-Allow-Headers','content-type');
  // 跨域允许的请求方式
  res.header('Access-Control-Allow-Methods','DELETE,PUT,POST,GET,OPTIONS');
  if(req.method.toLowerCase() == 'options')
      res.send(200); // 让options 尝试请求快速结束
  else
      next();
})



//3添加到需要上传一个name属性为pic的单文件上传路由：upload调用single方法传入需上传文件的name属性
app.post("/upfile", upload.single("file"), async (req, res) => {
  res.send({
    //post上传的文件信息（单个文件，当使用single方法时）
    file: req.file,
    //post提交的其他数据
    body: req.body,
  });
});


//解析post的json数据
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//api子路由
app.use('/api', require('./router/api/index'));

//404错误处理：上面都没有匹配的路由，参数3 next可以去掉
app.use((req, res) => {
  res.status(404).send("404 Not Found");
});

server.listen(config.port, "0.0.0.0", () => {
  console.log(`server running at port ${config.port}`);
});
